﻿using System;
using System.Threading.Tasks;
using AntUnion.FrameWork.Model.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using AntUnion.FrameWork.Util;
using AntUnion.FrameWork.Web.Extend;
using System.Linq;
using System.Net.Mail;
using AntUnion.FrameWork.Web.Service;
using RM.Common.DotNetEamil;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class LoginController : ControllerBase
    {
        public LogService logService = new LogService();
        private readonly mtContext _context;
        private readonly SmtpSettings _emailSender;
        public LoginController(mtContext context, SmtpSettings emailSender)
        {
            _context = context;
            _emailSender = emailSender;
        }
        public IActionResult Index(string language = "manage-zh-CN")
        {
            string defaultLanguage = "zh-CN";
            if (language == "manage-en-US")
            {
                defaultLanguage = "en-US";
            }
            ViewBag.webFrontTitle = _context.TbSystemConfigs.FirstOrDefault(k => k.MenuName == "webFrontTitle" && k.Language == defaultLanguage).Value;
            ViewBag.webAfterName = _context.TbSystemConfigs.FirstOrDefault(k => k.MenuName == "webAfterName" && k.Language == defaultLanguage).Value;
            return View();
        }
        [HttpPost]
        public async Task<JsonResult> Login(string UserName, string UserPwd, string validCode)
        {
            Result res = new Result();
            try
            {
                string ip = HttpContext.Connection.RemoteIpAddress.ToString();
                string ipAddress = "";
                if (ip != "::1")
                {
                    string[] ips = ip.Split('.');
                    if (ips.Length == 4)
                    {
                        try
                        {
                            IPModel iPModel = HttpUtil.HttpGet($"http://whois.pconline.com.cn/ipJson.jsp?ip={ip}&json=true").ToObject<IPModel>();
                            ipAddress = iPModel.addr;
                        }
                        catch
                        {
                            ipAddress = "";
                        }
                    }
                }
                if (ip.Contains("::"))
                {
                    var realip = HttpContext.Request.Headers["X-Real-IP"].FirstOrDefault();
                    if (realip != null)
                    {
                        ip = realip;
                        try
                        {
                            IPModel iPModel = HttpUtil.HttpGet($"http://whois.pconline.com.cn/ipJson.jsp?ip={ip}&json=true").ToObject<IPModel>();
                            ipAddress = iPModel.addr;
                        }
                        catch
                        {
                            ipAddress = "";
                        }
                    }
                }
                HttpContext.Session.TryGetValue("ValidateCode", out byte[] ValidateCode);
                if (ValidateCode != null)
                {
                    string Code = ByteConvertUtil.Deserialize<string>(ValidateCode).ToString();
                    if (Code == validCode)
                    {
                        string EncryptPwd = SecurityUtil.EncryptPwd(UserPwd);
                        TbUser data = await _context.TbUsers.FirstOrDefaultAsync(k => k.LoginName == UserName && k.LoginPwd == EncryptPwd && k.Isdel == 0);
                        if (data != null)
                        {
                            if (data.State == 1)
                            {
                                data.LastIp = ip;
                                data.LastTime = DateTimeUtil.Now;
                                logService.AddLoginLogs(HttpContext, data.LoginName, data.Id, 1, "loginSucceeded", ip, ipAddress, 0);
                                AdminModel model = new AdminModel
                                {
                                    Id = data.Id,
                                    UserName = data.UserName,
                                    LoginName = data.LoginName,
                                    State = data.State,
                                    Pid = data.Pid,
                                    Level = data.Level,
                                    UserType = 0,
                                    SessionId = HttpContext.Session.Id
                                };
                                HttpContext.Session.Set("User", ByteConvertUtil.Serialize(model));
                                HttpContext.Response.Cookies.Append("User", UserName + "|" + UserPwd, new CookieOptions
                                {
                                    Expires = DateTime.Now.AddHours(expires)
                                });
                                _context.SaveChanges();
                                res.Code = 0;
                                res.Data = "loginSucceeded";
                            }
                            else
                            {
                                logService.AddLoginLogs(HttpContext, data.LoginName, data.Id, 0, "loginManagementSystemFailed", ip, ipAddress, 0);
                                res.Code = 1;
                                res.Data = "accountDisabled";
                            }
                        }
                        else
                        {
                            logService.AddLoginLogs(HttpContext, UserName, 0, 0, "loginManagementSystemFailed", ip, ipAddress, 0);
                            res.Code = 1;
                            res.Data = "accountPasswordError";
                        }
                    }
                    else
                    {
                        logService.AddLoginLogs(HttpContext, UserName, 0, 0, "loginManagementSystemFailed", ip, ipAddress, 0);
                        res.Code = 1;
                        res.Data = "verificationCodeError";
                    }
                }
                else
                {
                    logService.AddLoginLogs(HttpContext, UserName, 0, 0, "loginManagementSystemFailed", ip, ipAddress, 0);
                    res.Code = 1;
                    res.Data = "enterVerificationCode";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.Message;
                return new JsonResult(res);
            }
        }

        public void AddLoginLogs(string loginName, int operatorId, int state, string cont)
        {
            LoginLog log = new LoginLog
            {
                Name = loginName,
                Cont = cont,
                Operator = operatorId,
                Source = 0,
                State = state,
                Addtime = DateTimeUtil.Now
            };
            string ip = HttpContext.Connection.RemoteIpAddress.ToString();
            if (ip != "::1")
            {
                string[] ips = ip.Split('.');
                if (ips.Length == 4)
                {
                    try
                    {
                        IPModel iPModel = HttpUtil.HttpGet($"http://whois.pconline.com.cn/ipJson.jsp?ip={ip}&json=true").ToObject<IPModel>();
                        log.Ipaddress = iPModel.addr;
                    }
                    catch { }
                }
            }
            log.Ip = ip;
            _context.LoginLogs.Add(log);
            _context.SaveChangesAsync();
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetValidateCode()
        {
            string code = ValidateCode.CreateValidateCode(5);
            HttpContext.Session.Set("ValidateCode", ByteConvertUtil.Serialize(code));
            byte[] bytes = ValidateCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }

        public IActionResult NeedLogin()
        {
            return View();
        }
    }
}